const model = require('../models/articleModel'),
  msgModel = require('../models/msgModel'),
  errCode = require('../../conf/errorCode'),
  wrap = require('../helper/wrap'),
  moment = require('moment'),
  conf = require('../../conf/const'),
  util = require('../helper/util'),
  _ = require('lodash'),
  {parseIntPageSize} = require('./commonService');

const DATE_FORMAT = 'YYYY-MM-DD HH:mm';

exports.addPost = function(
  {title, content, categoryId, carIds, channel, authorId, videoInfo},
  editorId,
  callback,
) {
  var tmp = util.firstKeyOfNull(
    {title, content, categoryId, carIds, authorId, channel},
    ['title', 'content', 'categoryId', 'carIds', 'authorId', 'channel'],
  );
  if (tmp != null) {
    return callback({errNo: errCode.LESS_OF_DATA_ERROR, extraMsgs: tmp});
  }
  model.add(
    wrap.changeData(
      {title, content, categoryId, carIds, authorId, channel, videoInfo},
      wrap.names.post,
      wrap.names.front,
      wrap.names.end,
    ),
    (err, result) => {
      if (err) return callback(err);
      return callback(null, {id: result.insertId});
    },
  );
};


exports.addPostForUser = async function(title, content, authorId, callback) {
  var tmp = util.firstKeyOfNull(
    {
      title,
      content,
    },
    ['title', 'content'],
  );
  if (tmp != null) {
    return callback({
      errNo: errCode.LESS_OF_DATA_ERROR,
      extraMsgs: tmp,
    });
  }
  //let validate = await util.promiseify(checkContentValidate)(content);
  //if (!validate) {
    //return callback({errNo: errCode.INVALID_CONTENT_ERROR});
  //}
  let categoryId = 5;
  model.addPostForUser(
    {
      categoryId,
      title,
      content,
      authorId,
    },
    (err, result) => {
      if (err) return callback(err);
      return callback(null, {
        id: result.insertId,
      });
    },
  );
};

exports.updatePost = function(
  postId,
  {title, content, categoryId, carIds, authorId, channel, videoInfo},
  editorId,
  callback,
) {
  var tmp = util.firstKeyOfNull(
    {title, content, categoryId, carIds, authorId, channel},
    ['title', 'content', 'categoryId', 'carIds', 'authorId', 'channel'],
  );
  if (tmp != null) {
    return callback({errNo: errCode.LESS_OF_DATA_ERROR, extraMsgs: tmp});
  }

  return model.updatePost(
    postId,
    wrap.changeData(
      {
        title,
        content,
        categoryId,
        carIds,
        authorId,
        editorId,
        channel,
        videoInfo,
      },
      wrap.names.post,
      wrap.names.front,
      wrap.names.end,
    ),
    (err, result) => {
      if (err) return callback(err);
      return callback(null, {
        affectData: result.affectedRows,
        updatedData: result.changedRows,
      });
    },
  );
};

exports.deletePostByIds = async function(ids, callback) {
  if (_.isString(ids)) {
    ids = ids.trim().split(',');
    if (
      !_.every(ids, function(value) {
        return util.isIntegerLike(value);
      })
    ) {
      return callback({errNo: errCode.INVALID_FORMAT_ERROR, extraMsgs: 'ids'});
    }
  } else if (_.isNumber(ids)) {
    ids = [ids];
  } else if (
    !_.isArray(ids) ||
    !_.every(ids, function(value) {
      return util.isIntegerLike(value);
    })
  ) {
    return callback({errNo: errCode.INVALID_FORMAT_ERROR});
  }
  if (ids.length == 0) {
    return callback(null, {deleted: 0});
  }
  //获取详情
  for (let i = 0, len = ids.length; i < len; i++) {
    let postDetail = await util.promiseify(model.getPostById)(ids[i]),
      msgObj = {};
    msgObj.type = 0;
    msgObj.uid = postDetail[0].authorId;
    msgObj.content = ids[i];
    await util.promiseify(msgModel.add)(msgObj);
  }
  model.deletePostByIds(ids, (err, result) => {
    if (err) return callback(err);
    return callback(null, {
      deleted: result.changedRows,
    });
  });
};

exports.getPostByPage = function(channel, page, size, callback) {
  let errMsgs = null;
  [errMsgs, page, size] = parseIntPageSize(page, size);

  if (errMsgs == null)
    model.getPostByPage(channel, page, size, (err, _rel) => {
      _rel.list.map(item => {
        item.createTime = util.formatTime(item.createTime);
      });

      if (err) {
        return callback(err);
      } else {
        return callback(null, _rel);
      }
    });
  else callback({errNo: errCode.INVALID_PARAM_ERROR, extraMsgs: errMsgs});
};

exports.getPostById = function(postId, callback) {
  let tmp = util.findInvalidKeyBy(
    {postId},
    {
      postId: v => {
        return util.isIntegerLike(v);
      },
      //userId       : (v) => { return util.isIntegerLike(v); },
    },
  );
  if (tmp != null) {
    callback({errNo: errCode.INVALID_PARAM_ERROR, extraMsgs: tmp});
    return;
  }

  model.getPostById(postId, (err, rslt) => {
    if (err == null) callback(null, rslt);
    else callback(err, null);
  });
};
exports.getPostCategory = function(callback) {
  model.getPostCategory(callback);
};
